<?php

/**
 * ads actions.
 *
 * @package    ndirou_affaire
 * @subpackage ads
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class adsActions extends sfActions
{
 /**
  * Executes index action
  *
  * @param sfRequest $request A request object
  */
  public function executeIndex(sfWebRequest $request)
  {
    $this->forward('default', 'module');
  }
  
  /**
   * 
   */
  public function executeAdsListBySubCategory(sfWebRequest $request){
  	$subCategory = $request->getParameter('subcat_id');
  	$this->aAds = Doctrine_core::getTable('Ads')->getAdsListByCategorie($subCategory);
  }
  
  /**
   * Detail annonce
   * 
   */
  public function executeDetail(sfWebRequest $request){
      $this->ads = $this->getRoute()->getObject();
      if( $this->ads->isActive() ){
        $this->getUser()->setAttribute('lastAds_id', $this->ads->id);
        // mettre a jour le compteur de consultation
        $this->ads->updateCounter();
      }else{
          $this->redirect404();
      }
  }
  
  
  
  /**
   * Liste des bons plans
   */
  public function executeBonPlanList(sfWebRequest $request){
      //$aAdsBonPlan = Doctrine_Core::getTable('Ads')->findBy('bonplan', 1);
      $this->ads = $this->getRoute()->getObject();
 
      $this->pager = new sfDoctrinePager( 'JobeetJob',   15 );
      $this->pager->setQuery($this->ads->getBonplanAdsQuery());
      $this->pager->setPage($request->getParameter('page', 1));
      $this->pager->init();
  
  }

    /**
   * Liste dernieres annonces
   */
  public function executeLastAdsList(sfWebRequest $request){
      //$aAdsBonPlan = Doctrine_Core::getTable('Ads')->findBy('bonplan', 1);
      $this->ads = $this->getRoute()->getObject();
 
      $this->pager = new sfDoctrinePager( 'JobeetJob',   15 );
      $this->pager->setQuery($this->ads->getLastAdsQuery());
      $this->pager->setPage($request->getParameter('page', 1));
      $this->pager->init();
  
  }


  
  /**
   * Deposer une annonce
   */
  public function executeCreateNewAds(sfWebRequest $request){
    
   if( $this->getUser()->isauthenticated() ){
        $this->form = new NewAdsForm();
        $this->form->setDefault('seller_id', $this->getUser()->getAttribute('sellerId'));
        $this->form->setDefault('status_id', 0);
        if( $request->isMethod('post') && $request->hasParameter('newAds') ){
                $data = $request->getParameter('newAds');
                if($request->isMethod('post')){
                        $files = $request->getFiles('newAds');
                        $this->form->bind($data,$files);
                        if($this->form->isValid()){
                            $date['description'] = utf8_encode($date['description']);
                            $date['title'] = utf8_encode($date['title']);
                            $ads = $this->form->save();
                            $this->getUser()->setFlash('success', 'Votre annonce a bien été créée, elle sera mise en ligne après la validation de notre équipe.');
                            // envoyer un mail au admin pour lui informer de la nouvelle annonce
                            $this->dispatcher->notify(new sfEvent($this, 'admin.newAds',array( 
                                'from' => $this->form->getObject()->Seller->email, 
                                'message' => 'ID:' . 'http://www.bay3wachira.com/back.php/adses/' . $this->form->getObject()->id . '/edit' . '- slug:' .$this->form->getObject()->slug,
                            )));
                            $this->redirect('@adsCreateOk');
                        }
                }
        }
    
    }else{
        $this->redirect('@addacount');
    }
    
  }
  	
    /**
     * New Ads success
     */
    public function executeCreateNewAdsOk(sfWebRequest $request) {
    }

    /**
     * sendMailToSeller
     */
    function executeSendMailToSellerAjax(sfWebRequest $request){
       // if( $request->isXmlHttpRequest() ){
        //$this->ads = $this->getRoute()->getObject();
        $id = $this->getUser()->getAttribute('lastAds_id');
        $this->ads = Doctrine_Core::getTable('Ads')->find($id);
        $this->setLayout('popin');
        $this->form = new ContactSellerForm($this-> ads);

        if( $request->isMethod('post') && $request->hasParameter('contactSeller') ){
            $data = $request->getParameter('contactSeller');
            if($request->isMethod('post')){
                $this->form->bind($data);
                if($this->form->isValid()){
                    $this->dispatcher->notify(new sfEvent($this, 'seller.bayerContact',array( 
                                'to' => $this->form->getValue('seller_email'), 
                                'from' => $this->form->getValue('bayer_email'), 
                                'name' => $this->form->getValue('bayer_name'), 
                                'adsTitle' => $this->form->getValue('title'),
                                'body' => $this->form->getValue('message'),
                        )));
                        
                    // TODO: stocker les messages
                    $msg = new BayerMessage();
                    $msg->ads_id = $id;
                    //$msg->bayer_id = $this->getUser()->getAttribute('sellerId');
                    $msg->message = 'FROM:' . $this->form->getValue('bayer_email') . ' <br/>' .$this->form->getValue('message');
                    $msg->save();
                }
            }
        }

       // }return $this->renderText('Erreur Système est survenue....');
    }
    
    /**
     * Modifier une annonce
     */
    public function executeUpdateAds(sfWebRequest $request) {
        //$id = $this->getUser()->getAttribute('lastAds_id');
        $this->setLayout('layout');
        $id=$request->getParameter('ads_id');
        $this->ads = Doctrine_Core::getTable('Ads')->find( $id );
        
         if( $this->getUser()->isauthenticated() ){
            $this->form = new NewAdsForm($this->ads);
            //$this->form->setDefault('seller_id', $this->getUser()->getAttribute('sellerId'));
            //$this->form->setDefault('status_id', 0);
            if( $request->isMethod('post') && $request->hasParameter('newAds') ){
                    $data = $request->getParameter('newAds');
                    if($request->isMethod('post')){
                            $files = $request->getFiles('newAds');
                            $this->form->bind($data,$files);
                            if($this->form->isValid()){
                                //echo $slug = Doctrine_Inflector::urlize($this->form->getValue('title')); npn fait automatikement :)
                                $ads = $this->form->save();
                                $this->getUser()->setFlash('success', 'Votre annonce a bien été mise à jour.');
                                $this->redirect('@adsDetail?subcat='. Doctrine_Inflector::urlize($this->ads->SubCategory->title). '&slug='.$this->ads->slug);
                            }
                    }
            }

        }else{
            $this->getUser()->setAttribute('referer', '@updateAds?ads_id='.$id.'&slug=modifier-annonce');
            $this->redirect('@login');
        }
            
    }
    
    /**
     * Delete Ads
     */
    public function executeDeleteAds(sfWebRequest $request) {
        //$id = $this->getUser()->getAttribute('lastAds_id');
        //$ads = Doctrine_Core::getTable('Ads')->find($id);
        $ads = $this->getRoute()->getObject();
        $sellerId = $this->getUser()->getAttribute('sellerId');
        if( $ads->Seller->id == $sellerId && $this->getUser()->isAuthenticated() ){
            $ads->changeStatus();
            $this->getUser()->setFlash('success', 'Votre annonce est désormais supprimer');
            $this->redirect('@homepage');
        }else{
            $this->redirect('@login');
        }
    }
    
    /**
     * signaler un abus
     */
    public function executeSignalerAbus(sfWebRequest $request){
        $this->setLayout('popin');
        $id = $this->getUser()->getAttribute('lastAds_id');
        $ads = Doctrine_Core::getTable('Ads')->find($id);

        $this->form = new ContactSellerForm($ads);
        $this->form->useFields( array('bayer_email','message') );
        
        if( $request->isMethod('post') && $request->hasParameter('contactSeller') ){
            $data = $request->getParameter('contactSeller');
            //echo '<pre>' . print_r($data,1) . '</pre>';
            if($request->isMethod('post')){          
                    $this->dispatcher->notify(new sfEvent($this, 'ads.signalabus',array( 
                          'from' => $data['bayer_email'],
                          'message' => $data['message'] . " [TITLE] = " . $data['title'] . " [ANNONCEUR] = " . $data['seller_email'] ,
                          'url' => 'annonces-gratuites/'. Doctrine_Inflector::urlize($ads->SubCategory->title). '/'.$ads->slug,
                    )));
                    //$this->getUser()->setFlash('success', "L'équipe de Bay3wachira vous remercie pour votre collaboration.");
                    //$this->redirect('@adsDetail?subcat='. Doctrine_Inflector::urlize($ads->SubCategory->title). '&slug='.$ads->slug);

            }
        }
        
    }
    
    
    
     /**
     * Envoyer à un ami
     */
    public function executeSendToFriend(sfWebRequest $request){
        $this->setLayout('popin');
        $this->form = new SendAdsToFriendForm;
        
        if( $request->isMethod('post') && $request->hasParameter('sendFriend') ){
            $data = $request->getParameter('sendFriend');
            if($request->isMethod('post')){
                    $id = $this->getUser()->getAttribute('lastAds_id');
                    $ads = Doctrine_Core::getTable('Ads')->find($id);
                    
                    $this->dispatcher->notify(new sfEvent($this, 'ads.sendToFriend',array( 
                          'from' => $this->form->getValue('sender'),
                          'to'=> $this->form->getValue('receiver'),
                          'message' => $this->form->getValue('message'),
                          'url' => 'annonces-gratuites/'. Doctrine_Inflector::urlize($ads->SubCategory->title). '/'.$ads->slug,
                    )));
            }
        }
        
    }
    
    /**
     * getSubcategories list by category_id
     */
    public function executeGetSubCategoriesByCategoryIdAjax(sfWebRequest $request){
        if( $request->isXmlHttpRequest() ){
            $this->aSubCategories = Doctrine_Core::getTable('SubCategory')->getSubcategoriesByCategoryId( $request->getParameter('cat_id') );
        }else{
            return $this->renderText(0);
        }
    }
}
